package com.heima.wemedia.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.common.contants.ScheduleConstants;
import com.heima.common.dtos.ResponseResult;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.feign.TaskFeign;
import com.heima.utils.common.JsonUtils;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 需求：每隔1秒扫描Redis中满足执行时间的文章，做定时发布
 */
@Component
@Slf4j
public class WmNewsTaskJob {
    @Autowired
    private TaskFeign taskFeign;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsService wmNewsService;
    /**
     * 每隔1秒执行1次
     *  fixedRate: 固定频率，单位毫秒
     */
    @Scheduled(fixedRate = 1000)
    public void scanNewsByTask(){
        //获取到满足执行时间的任务
        ResponseResult<List<Task>> responseResult = taskFeign.pollTask(ScheduleConstants.TASK_TOPIC_NEWS_PUBLISH);

        if(responseResult.getCode().equals(200)){
            //取出任务列表
            List<Task> taskList = responseResult.getData();

            List<Integer> ids = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(taskList)){
                for(Task task:taskList){
                    //取出文章
                    String parameters = task.getParameters();
                    WmNews wmNews = JsonUtils.toBean(parameters, WmNews.class);
                    //根据文章ID查询文章数据
                    wmNews = wmNewsService.getById(wmNews.getId());
                    //发布文章
                    wmNewsAutoScanService.saveApArticle(wmNews);

                    ids.add(wmNews.getId());
                }
                log.info("定时发布了文章 {} id:" +ids);
            }
        }
    }

}
